import React, { useEffect, useRef, useState , useContext } from 'react';
import { Button,Space,Modal,message,Select,TreeSelect  } from 'antd';
import { CaretRightOutlined, FileTextOutlined, InstagramOutlined,DeleteOutlined } from '@ant-design/icons';
import WorkbenchesIcon from '@/components/workbenches/icons';
import { useTranslation } from 'react-i18next';
import MonacoEditor from './monacoEditor';
import TabResult from './tabResult';
import { createMetricQuery,metricTree,executeSql,deleteMetricQuery,getMetricQueryInfo,updateMetricQuery } from '@/client/api';
// import { deleteMetricQuery } from '@/client/api/query';
import { useRequest } from 'ahooks';
import { WorkbenchesContext, } from '@/components/workbenches/workbenches-context';
const { confirm } = Modal;

// interface DataModelProps {
//   queryName: string;
//   datasourceId: number
// }

const DataModel: React.FC = () => {
  const { currentItem,getCurrentItemChange,treeData,delTabChange } = useContext(WorkbenchesContext);

  const { t } = useTranslation();
  const tabContentRef = useRef<any>(null);
  const [code, setCode] = useState<string>('');
  const [open, setOpen] = useState<boolean>(false);
  const [metricList, setMetricList] = useState<any>([]); // 树形选择数据
  // const [executeList, setExecuteList] = useState<any>([]); // 执行sql返回数据
  const [value, setValue] = useState<string>(); // 当前树形选择
  const [executeName, setExecuteName] = useState<string>();

  // 执行查询sql接口
  const { run: execute } = useRequest(
    async (params) => {
      return await executeSql(params);
    },
    {
      manual: true,
      onSuccess: res => {
        if (res.data.code === 0) {
          // setExecuteList(res.data.data);
          tabContentRef.current?.onEdit('', 'add',res.data.data);
          setOpen(true)
        }else {
          message.error(res.data.msg || '执行失败');
          return null
        }
      },
      onError: (error) => {
        message.error("请求失败：" + error.message);
        return null
      }
    },
  );

  // 查看详情
  const { run: getDetail } = useRequest(
    async () => {
      return await getMetricQueryInfo({id: currentItem.key.split('_')[1]});
    },
    {
      manual: true,
      onSuccess: res => {
        if (res.data.code === 0) {
          setValue(res.data.data.datasourceId)
          setCode(res.data.data.querySql)
          return res.data.data
        }else {
          message.error(res.data.msg || '查询失败');
          return null
        }
      },
      onError: (error) => {
        message.error("请求失败：" + error.message);
        return null
      }
    },
  );

  const executeQuery = async() => {
    if (!code) {
      message.warning('请输入sql语句');
      return
    }
    if (!value) {
      message.warning('请选择数据源');
      return
    }
    let node = treeData.filter((item: any) => {
      return item.id == value
    })
    let executeName = node[0].name + '/' + node[0].children[0].name
    setExecuteName(executeName)
    let schemaName = node[0].children[0].name
    let params = { 
      current: 1,
      size: 10,
      datasourceId:value,
      sql:code,
      schemaName,
    };
    await execute(params)
  };

  const beautifyCode = () => {
    // 添加美化代码的逻辑
  };

  const getNowTime = () => {
    // 1. 创建 Date 对象
    const now = new Date();

    // 2. 获取各时间分量
    const year = now.getFullYear();    // 年
    const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月 (0-11 → 1-12)
    const day = now.getDate().toString().padStart(2, '0');          // 日
    const hours = now.getHours().toString().padStart(2, '0');       // 时
    const minutes = now.getMinutes().toString().padStart(2, '0');   // 分
    const seconds = now.getSeconds().toString().padStart(2, '0');   // 秒

    // 3. 拼接成完整日期时间
    const fullDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

    return fullDateTime;
  }

  // 保存查询
  const saveCode = async() => {
    if (!code) {
      message.warning('请输入sql语句');
      return
    }
    if (!value) {
      message.warning('请选择数据库');
      return
    }
    confirm({
      content: '是否保存当前配置？',
      okText: '保存',
      onOk() {
        return new Promise<void>(async(resolve, reject) => {
          try {
            // const [datasourceId, queryName] = value.split(':').map(s => s.trim())
            let node = treeData.filter((item: any) => {
              return item.id == value
            })
            let queryName = node[0].name + getNowTime() 
            let params = { querySql: code ,queryName, datasourceId:value,id:'' }
            let res
            if (currentItem?.label) {
              params['id'] = currentItem?.key.split('_')[1]
              res = await updateMetricQuery(params);
            }else {
              delete params.id
              res = await createMetricQuery(params);
            }
            
            if (res) {
              resolve();
              message.success('保存成功');
              getCurrentItemChange(currentItem?.label ? currentItem?.key : 'Q_'+ res?.data?.data + '')
            } else {
              reject();
              message.error(res || '保存失败');
            }
          } catch (error) {
            reject();
            message.error('保存失败，请重试');
          }
        }).catch(() => console.log('Oops errors!'));
      },
      onCancel() {},
    });
  };

  // 删除查询
  const delQuery = async() => {
    confirm({
      content: '是否删除当前查询？',
      okText: '删除',
      onOk() {
        return new Promise<void>(async(resolve, reject) => {
          try {
            let res = await deleteMetricQuery({ id:currentItem?.key.split('_')[1] });
            if (res) {
              console.log(res,currentItem, 'delQuery')
              message.success('删除成功');
              delTabChange({ key: currentItem.key });
              resolve();
            } else {
              message.error(res || '删除失败');
              reject();
            }
          } catch (error) {
            reject();
            message.error('删除失败，请重试');
          }
        }).catch(() => console.log('Oops errors!'));
      },
      onCancel() {},
    });
  };

  const handleEditorChange = (value: string | undefined) => {
    if (value !== undefined) {
      setCode(value);
    }
  };

  // const getMetricTree = async () => {
  //   let res = await metricTree({});
  //   let list  = res.data.code == 0 ? res.data.data : []
   
  //   setMetricList(list)
  //   console.log(list, metricList,'list')
  // }
  // const extractSchemaNodes = (data:any)=> {
  //   let schemas:any = [];
  
  //   data.forEach((node:any) => {
  //     // 确保当前节点有子节点
  //     if (node.children && Array.isArray(node.children)) {
  //       node.children.forEach((child:any) => {
  //         // 检查子节点的类型
  //         if (child.nodeType === 'Schema') {
  //           schemas.push(child);
  //         }
  //       });
  //     }
  //   });
  
  //   return schemas;
  // }

  const { run: getMetricTree } = useRequest(
    async () => {
      return await metricTree({});
    },
    {
      manual: true,
      onSuccess: res => {
        if (res.data.code === 0) {
          let list = res.data.data && res.data.data.length > 0 ? res.data.data : [];
          filterSchemas(list);
          setMetricList(list);
          console.log(res, list,currentItem,value, 'metricTreeData');
        }
      },
    },
  );

  
  function filterSchemas(nodes:any) {
    if (!nodes || nodes.length === 0) {
      return []
    }
    nodes.forEach((node: any) => {
      node.title = node.name
      node.value = node.id  
      node.disabled = true  
      node.children.forEach((child:any) => {  
        child.title = child.name
        child.value = child.id
        delete child.children;
      })
      node.children = node.children.filter((child:any) => {return child.nodeType == 'Schema'})
    });
  }

  const onChange = (newValue: any) => {
    setValue(newValue);
  };
  // 树形结构接口
  // useEffect(() => {
  //   getMetricTree();
  // }, []);

  useEffect(() => {
    if (currentItem?.label) {
      getDetail()
    }else {
      setCode('')
    }
  }, [currentItem]);


  return (
    <div className='h-full'>
      <div className='mb-2 ml-2 mr-10 flex items-center justify-between'>
        <Space>
          <Button onClick={executeQuery} className='dark:border-btnDarkBorder'>
            <CaretRightOutlined />
            {t('w_execute')}
          </Button>
          <Button onClick={beautifyCode} className='dark:border-btnDarkBorder'>
            <InstagramOutlined />
            美化
          </Button>
          <Button onClick={saveCode} className='dark:border-btnDarkBorder'>
            <FileTextOutlined />
            保存
          </Button>
          <div className='mx-2 w-1 h-6 border-r-2 border-borderColor dark:border-darkBorderColor'></div>
          <Button className='dark:border-btnDarkBorder' onClick={delQuery}>
            <DeleteOutlined />
          </Button>
        </Space>
        {/* <TreeSelect
          listHeight={ 500 }
          style={{ width: 200 }}
          value={value}
          treeData={metricList}
          placeholder="请选择数据源"
          treeDefaultExpandAll
          onChange={onChange}
        /> */}
        <Select value={value || ''} style={{ width: 200 }} onChange={onChange}>
         {
            treeData.map((i: any) => {
              return (
                <Select.Option value={i.key}>
                  <div className='flex items-center w-40 ' title={i.name}>
                    <WorkbenchesIcon type='starrocks' />
                    <div className='ml-2'> {i.name}</div>
                  </div>
                </Select.Option>
              )
            })
          }
        </Select>
      </div>
      <MonacoEditor value={code} language={'sql'} height={790} onChange={handleEditorChange} />
      <TabResult ref={tabContentRef} open={open} executeName={executeName} onClose={() => { setOpen(false);}}/>
    </div>
  );
};

export default DataModel;